﻿/*
 * 开发者：LYC
 * 
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Partner.MVC.Models;
using Newtonsoft.Json;
using System.Transactions;
using System.Data.Entity;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
namespace Partner.MVC.Controllers
{
    public class UserCenterController : Controller
    {
        // 实例化上下文集合
        GuyEntities db = new GuyEntities();

        #region 我的收藏
        /// <summary>
        ///  我的收藏 -- 房源收藏
        /// </summary>
        /// <returns></returns>
        public ActionResult HouseCollect()
        {
            var user = Session["LoginUser"] as User_Info;
            var query = from c in db.Collect
                        join h in db.House_Source on c.House_Id equals h.House_Id
                        where c.Use_Id == user.Use_Id
                        //select Tuple.Create(
                        //  c.House_Id,
                        //);
                        select h;
            ViewBag.House = query.ToList();
            ViewBag.HouseWork = query.Where(a => a.House_Type == "伙办办公").ToList();
            ViewBag.HouseApment = query.Where(a => a.House_Type == "伙办公寓").ToList();
            ViewBag.HouseShop = query.Where(a => a.House_Type == "伙办商铺").ToList();
            return View();
        }
        /// <summary>
        /// 批量删除收藏的房源
        /// </summary>
        /// <param name="House_Id"></param>
        /// <returns></returns>
        public int Delete(string House_Id)
        {
            string[] id = House_Id.Split(',');

            foreach (var i in id)
            {
                int s = Convert.ToInt32(i);
                db.House_Source.Remove(db.House_Source.Where(n => n.House_Id == s).FirstOrDefault());
            }
            return db.SaveChanges();
        }

        #endregion

        #region 我的预约
        /// <summary>
        ///  我的预约 -- 看房预约
        /// </summary>
        /// <returns></returns>
        public ActionResult SeeHouse()
        {
            var user = Session["LoginUser"] as User_Info;
            var list = from a in db.House_Appoint
                       join h in db.House_Source on a.House_Id equals h.House_Id
                       where a.App_CreatePeople == user.Use_Id
                       select new
                       {
                           a.House_Id,
                           a.App_Time,
                           h.House_Type,
                           h.House_Name,
                           h.House_Telphone,
                           h.House_CreatePeople,
                           h.House_Address,
                           h.House_Area,
                           h.House_FloorHigh,
                           h.House_FreeLease,
                           h.House_Img,
                       };
            //select h;
            var house = from o in list.ToList()
                        select Tuple.Create(
                         o.App_Time,
                         o.House_Type,
                         o.House_Name,
                         o.House_Telphone,
                         o.House_CreatePeople,
                         o.House_Address,
                         o.House_Id
                         );
            ViewBag.HouseList = house.ToList();
            return View();
        }
        /// <summary>
        ///  我的预约 -- 服务预约
        /// </summary>
        /// <returns></returns>
        public ActionResult MoveHouse()
        {
            var user = Session["LoginUser"] as User_Info;
            var list = from o in db.House_Order
                       join s in db.House_Server on o.S_Id equals s.S_Id
                       where o.Use_Id == user.Use_Id && o.O_Status == 1 && o.O_Status != 2   //0未支付  1 已支付  2 用户删除   3 商家删除
                       select new
                       {
                           s.S_Id,
                           o.O_Num,
                           o.O_Price,
                           o.O_Company,
                           s.S_Type,
                           s.S_Telphone
                       };
            var HouseList = from a in list.ToList()
                            select Tuple.Create(
                             a.S_Id, a.O_Num, a.O_Price, a.O_Company,
                         a.S_Type, a.S_Telphone
                            );
            return View(HouseList);
        }
        /// <summary>
        /// 批量删除预约信息
        /// </summary>
        /// <param name="House_Id"></param>
        /// <returns></returns>
        public int DeleteAll(string House_Id)
        {
            var user = Session["LoginUser"] as User_Info;
            string[] id = House_Id.Split(',');

            foreach (var i in id)
            {
                int s = Convert.ToInt32(i);
                db.House_Appoint.Remove(db.House_Appoint.Where(n => n.House_Id == s && n.App_CreatePeople == user.Use_Id).FirstOrDefault());
            }
            return db.SaveChanges();
        }
        #endregion

        #region 我的消息
        /// <summary>
        ///  我的消息 -- 系统消息
        /// </summary>
        /// <returns></returns>
        public ActionResult message()
        {
            var user = Session["LoginUser"] as User_Info;
            var list = db.House_Message.Where(a => a.Use_Id == user.Use_Id && a.IsDel != 2).OrderByDescending(a => a.M_Time).ToList();
            return View(list);
        }
        public ActionResult messageXX(int id)
        {
            var messModel = db.House_Message.Where(a => a.M_Id == id).FirstOrDefault();
            messModel.IsDel = 1;  // 将查看的这条消息标记为已读  0未读，1已读，2删除
            db.SaveChanges();
            return View(messModel);
        }
        /// <summary>
        /// 删除消息记录
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int DelMessage(House_Message model)
        {
            var upt = db.House_Message.Where(n => n.M_Id == model.M_Id).FirstOrDefault();
            upt.IsDel = 2;
            return db.SaveChanges();
        }
        #endregion

        #region 订单管理
        /// <summary>
        ///  订单管理 -- 投放记录
        /// </summary>
        /// <returns></returns>
        public ActionResult PutRecord()
        {
            var user = Session["LoginUser"] as User_Info;
            var list = db.House_Source.Where(a => a.House_CreatePeople == user.Use_Id && a.House_State != 2).ToList();
            return View(list);
        }
        /// <summary>
        /// 批量删除投放记录
        /// </summary>
        /// <param name="House_Id"></param>
        /// <returns></returns>
        public int ThrowRecord(string House_Id)
        {
            var user = Session["LoginUser"] as User_Info;
            string[] id = House_Id.Split(',');
            foreach (var i in id)
            {
                int s = Convert.ToInt32(i);
                //这个报错？
             //var lists=   db.House_Source.Where(n => n.House_Id == s && n.House_CreatePeople == user.Use_Id).FirstOrDefault();
             //lists.House_State = 3;  //   0未审核  1通过    2 驳回     3用户删除   4 管理员删除
             //db.Entry(lists).State = System.Data.EntityState.Modified;              
                var del = db.House_Source.Where(n => n.House_Id == s && n.House_CreatePeople == user.Use_Id).FirstOrDefault(); db.House_Source.Remove(del);
            }             
           
            return db.SaveChanges();
           
            
        }

        /// <summary>
        ///  订单管理 -- 委托记录
        /// </summary>
        /// <returns></returns>
        public ActionResult EntrustRecord()
        {
            var user = Session["LoginUser"] as User_Info;
            var list = db.House_Entrust.Where(a => a.E_CreatePeople == user.Use_Id && a.E_State != 2).ToList();   // 0未处理 1 已处理  2用户删除  3 管理员删除
           
            return View(list);
        }
        /// <summary>
        ///  订单管理 -- 我的订单
        /// </summary>
        /// <returns></returns>
        public ActionResult MyPay()
        {
            var user = Session["LoginUser"] as User_Info;
            var list = from o in db.House_Order
                       join s in db.House_Server on o.S_Id equals s.S_Id
                       where o.Use_Id == user.Use_Id && o.O_Status != 2   //0未支付  1 已支付  2 用户删除   3 商家删除
                       select new
                       {
                           s.S_Id,
                           o.O_Num,
                           o.O_Price,
                           o.O_Company,
                           s.S_Type,
                           s.S_Telphone,
                           o.O_Status,
                           o.O_Id
                       };
            var HouseList = from a in list.ToList()
                            select Tuple.Create(
                             a.S_Id, a.O_Num, a.O_Price, a.O_Company,
                         a.S_Type,
                         a.S_Telphone,
                         Tuple.Create(
                         a.O_Status,
                         a.O_Id
                         )
                            );

            var list1 = HouseList.Where(a => a.Item7.Item1 == 1).ToList(); // 1已支付
            var order = HouseList.Where(a => a.Item7.Item1 == 0).ToList(); // 0 未支付
            ViewBag.pay = list1;
            ViewBag.order = order;
            return View();
        }

        /// <summary>
        ///  用户 反填订单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult AddOrder(int id)
        {
            var user = Session["LoginUser"] as User_Info;
            var list = db.House_Server.Where(n => n.S_Id == id).FirstOrDefault();
            if (user == null)
            {
                return Content("<script>alert('请先登录！');location.href='/Partner/officeService';</script>");

            }
            else if (list.S_CreatePerson == user.Use_Id)
            {
                return Content("<script>alert('不能订阅自己的订单');window.history.back(-1)</script>");
            }

            else
            {
                return View(db.House_Server.Where(a => a.S_Id == id).FirstOrDefault());
            }
        }
        /// <summary>
        /// 删除订单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int DeletePay(int id)
        {
            var orderModel = db.House_Order.Where(n => n.O_Id == id).FirstOrDefault();
            orderModel.O_Status = 2;   //0未支付  1 已支付  2 用户删除   3 商家删除
            int i = db.SaveChanges();
            return i;
        }
        /// <summary>
        /// 用户  支付密码输入
        /// </summary>
        /// <returns></returns>
        public int PayMessage(string PayPwd, int PayID)
        {
            var user = Session["LoginUser"] as User_Info;
            if (user.Use_Pwd != PayPwd)
            {
                return 0;
            }
            else
            {
                return 1;
            }
        }
        ////获取用户银行卡
        public string GetUserBank()
        {
            var user = Session["LoginUser"] as User_Info;
            var list = db.BankCard.Where(n => n.B_Holder == user.Use_ReallyName && n.B_FastPay == 1).ToList();
            return JsonConvert.SerializeObject(list);
        }
        //支付
        public int PayBank(int Card, int Serve)
        {
            var user = Session["LoginUser"] as User_Info;
            //获取选择支付的 银行卡信息
            var BankList = db.BankCard.Where(n => n.B_Id == Card).FirstOrDefault();
            //获取要支付的 服务信息
            var Servelist = db.House_Order.Where(n => n.O_Id == Serve).FirstOrDefault();
            if (BankList.B_Balance >= Servelist.O_Price)
            {
                //如果余额比服务价格多 就执行支付
                BankList.B_Balance = BankList.B_Balance - Servelist.O_Price;
                Servelist.O_Status = 1;

                House_Message m = new House_Message();
                m.Use_Id = user.Use_Id;
                m.M_Title = "您的订单支付成功!";
                m.M_Content = "" + user.Use_Telphone + "您好，您在" + DateTime.Now.ToShortDateString() + "购买的" + Servelist.O_Company + "的服务已支付成功!。 ";
                m.M_Time = DateTime.Now;
                m.IsDel = 0;
                db.House_Message.Add(m);
                return db.SaveChanges();
            }
            else
            {
                return 0;
            }

        }
        //删除选中的 已支付的消息提示
        public int DeleteSelection(string MessageId)
        {
            string[] PayId = MessageId.Split(',');

            foreach (var i in PayId)
            {
                int s = Convert.ToInt32(i);
                var orderModel = db.House_Order.Where(n => n.O_Id == s).FirstOrDefault();
                orderModel.O_Status = 2;   //0未支付  1 已支付  2 用户删除   3 商家删除
            }
            return db.SaveChanges();
        }
        //我的消息  获取委托房源的信息
        public string GetTableMessage(int id)
        {
            var list = db.House_Source.Where(n => n.House_Id == id).FirstOrDefault();
            return JsonConvert.SerializeObject(list);
        }
        /// <summary>
        /// 添加订单
        /// </summary>
        /// <param name="ho"></param>
        /// <returns></returns>
        public ActionResult AddOrderDo(House_Order ho)
        {
            ho.O_Status = 0;
            var user = Session["LoginUser"] as User_Info;
            ho.Use_Id = user.Use_Id;
            var exists = db.House_Order.Where(n => n.S_Id == ho.S_Id && n.Use_Id == user.Use_Id).FirstOrDefault();

            if (user == null || user.Use_Name == "")
            {
                return Content("<script>alert('请先登录！');location.href='/Partner/officeService';</script>");

            }
            else if (exists != null)
            {
                return Content("<script>alert('您已添加此订单');location.href='/Partner/officeService';</script>");
            }
            else
            {
                db.House_Order.Add(ho);
                if (db.SaveChanges() > 0)
                {
                    return Content("<script>alert('下单成功！请尽快付款！');location.href='/UserCenter/MyPay';</script>");
                }
                else
                {
                    return Content("<script>alert('下单失败！请确保无误后重新下单！');location.href='/Partner/officeService';</script>");
                }
            }
        }

        #endregion

        #region 个人中心
        /// <summary>
        ///  个人中心 -- 个人资料
        /// </summary>
        /// <returns></returns>
        public ActionResult MyInfo()
        {
            var user = Session["LoginUser"] as User_Info;
            return View(db.User_Info.Where(a => a.Use_Id == user.Use_Id && a.IsUse == 1).FirstOrDefault());
        }
        /// <summary>
        ///  个人中心 -- 密码管理
        /// </summary>
        /// <returns></returns>
        public int PasswordManage(string OldPwd, string NewPwd)
        {
            var user = Session["LoginUser"] as User_Info;
            //根据登录的名称寻找数据
            var list = db.User_Info.Where(n => n.Use_Name == user.Use_Name).FirstOrDefault();
            if (list != null)
            {
                //如果数据不为空，判断输入的旧密码是否等于
                if (list.Use_Pwd == OldPwd)
                {
                    list.Use_Pwd = NewPwd;
                    int i = db.SaveChanges();
                    return i;
                }
                else
                {
                    return 101;
                }
            }
            else
            {
                return 102;
            }
        }
        /// <summary>
        /// 个人中心 -- 找回密码服务
        /// </summary>
        /// <param name="FindName"></param>
        /// <param name="FindPhone"></param>
        /// <returns></returns>
        public string FindPwd(string FindName, string FindPhone)
        {
            var list = db.User_Info.Where(n => n.Use_Name == FindName && n.Use_Telphone == FindPhone).FirstOrDefault();
            return JsonConvert.SerializeObject(list);
        }
        /// <summary>
        ///  个人中心 -- 我的钱包
        /// </summary>
        /// <returns></returns>
        public ActionResult PayManage()
        {
            var user = Session["LoginUser"] as User_Info;
            ViewBag.Name = user.Use_ReallyName;
            var cardList = db.BankCard.Where(a => a.B_Holder == user.Use_ReallyName && a.IsUse == 1).ToList();
            return View(cardList);
        }
        /// <summary>
        ///  个人中心 -- 我的钱包 绑定银行卡
        /// </summary>
        /// <param name="bankName"></param>
        /// <param name="realName"></param>
        /// <param name="bankCard"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public int addCard(string bankName, string realName, string bankCard, int type)
        {
            BankCard b = new BankCard();
            var exists = db.BankCard.Where(n => n.B_BankAccount == bankCard).FirstOrDefault();
            b.B_BankName = bankName;
            b.B_Holder = realName;
            b.B_BankAccount = bankCard;
            b.B_Type = 1;     // 1为储蓄卡  2为信用卡
            b.B_FastPay = 1;  // 0为未开通快捷支付
            b.B_Balance = 9000000;  // 余额默认为0
            b.IsUse = 1;
            if (exists == null)
            {
                db.BankCard.Add(b);
                return db.SaveChanges();
            }
            else
            {
                return 0;
            }


        }
        /// <summary>
        ///  个人中心 -- 我的钱包  解除绑定银行卡
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int delCard(int id)
        {
            var card = db.BankCard.Where(a => a.B_Id == id).FirstOrDefault();
            card.IsUse = 0;      //  0未使用 1可使用
            return db.SaveChanges();
        }
        /// <summary>
        /// 修改图片
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int UptImage(User_Info model)
        {
            //登陆传信息
            var user = Session["LoginUser"] as User_Info;
            //获取图片二进制流
            string base64str = model.Use_Img.Split(',')[1];
            //把二进制流转换成字节流
            byte[] data = Convert.FromBase64String(base64str);
            //Encoding.UTF8.get   
            string filename = DateTime.Now.ToString("yyyyMMddhhmmsss") + "." + model.Use_Img;
            string strflie = AppDomain.CurrentDomain.BaseDirectory + "Img\\";
            strflie += filename;
            var list = db.User_Info.Where(n => n.Use_Id == user.Use_Id).FirstOrDefault();
            list.Use_Img = "/img/" + filename;
            db.Entry(list).State = System.Data.EntityState.Modified;
            return db.SaveChanges();
        }

        /// <summary>
        /// 加载页面获取图片
        /// </summary>
        /// <param name="streamByte"></param>
        /// <returns></returns>
        //public System.Drawing.Image ReturnPhoto(byte[] streamByte)
        //{
        //    //登陆传信息
        //    var user = Session["LoginUser"] as User_Info;
        //    var imgs = db.User_Info.Where(n => n.Use_Id == user.Use_Id).FirstOrDefault();        
        //    byte[] byteArray = System.Text.Encoding.Default.GetBytes(imgs.Use_Img);
        //    System.IO              
        //    .MemoryStream ms = new System.IO
        //    .MemoryStream(byteArray);
        //    //System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
        //    //Image bmpt =   Bitmap.FromStream(ms); 
        //    Bitmap bitmap = new Bitmap(ms);
        //    return bitmap;
        //}
    }
        #endregion

}

